package cadtoolbox.utils;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.commons.math3.ode.events.EventHandler;

import cadtoolbox.model.AbstractInput;
import cadtoolbox.model.SequenceVertex;

public class MyEventHandler implements EventHandler {

	private HashMap<SequenceVertex,Integer> inputs; // the integer is the index in the y state array
	private double val = 1;
	
	public MyEventHandler(HashMap<SequenceVertex,Integer> inputs){
		this.inputs = inputs;
	}
	
	@Override
	public Action eventOccurred(double arg0, double[] arg1, boolean arg2) {
		
		return EventHandler.Action.RESET_STATE;
	}

	@Override
	public double g(double t, double[] y) {
		double value = val;
		ArrayList<Double> times = new ArrayList<Double>();
		for (SequenceVertex seq : inputs.keySet()){
			for(AbstractInput input: seq.inputs){
				if(input.hasSingularity() && !times.contains(input.getNextSingularityTime())){
					times.add(input.getNextSingularityTime());
					value *= t - input.getNextSingularityTime();
				}
			}
		}
		return value;
	}

	@Override
	public void init(double arg0, double[] arg1, double arg2) {

	}

	@Override
	public void resetState(double t, double[] y) {
		for(SequenceVertex seq : inputs.keySet()){
			for(AbstractInput input: seq.inputs){
				if (input.getNextSingularityTime() == t){
					y[inputs.get(seq)] = y[inputs.get(seq)] + input.f(t);
					input.consummeSingularity();
					if(input.hasSingularity()){ // has more singularity
						val = -val;
					}
				}
			}
		}

	}

}
